﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenTK;
using OpenTK.Graphics.OpenGL4;
using OpenTK.Input;
using System.Drawing;
using OpenTK.Graphics;
using Common;

namespace T15_LightMaps {
    class T15_LightMapsGameWindow : GameWindow {
        public T15_LightMapsGameWindow() {
            this.Load += T15_LightMapsGameWindow_Load;
            this.Resize += T15_LightMapsGameWindow_Resize;
            this.RenderFrame += T15_LightMapsGameWindow_RenderFrame;
            this.Unload += T15_LightMapsGameWindow_Unload;
            this.Width = 1024;
            this.Height = 768;
            this.Title = "T15_LightMapsGameWindow";

        }


        private void T15_LightMapsGameWindow_RenderFrame(object sender, FrameEventArgs e) {
            GL.ClearColor(.1f, .1f, .99f, .9f);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            Render();

            SwapBuffers();
            ProcessEvents();
        }

        ModelMesh mesh;
        Vao vao;
        Shader shader;
        Texture2D texture;
        Vbo<Vector3> vertexBuffer;
        Vbo<Vector2> uvBuffer;
        VertexAttribManager attribs = new VertexAttribManager();
        private void T15_LightMapsGameWindow_Load(object sender, EventArgs e) {

            VSync = VSyncMode.Off;
            GL.Enable(EnableCap.DepthTest);
            GL.DepthFunc(DepthFunction.Less);
            GL.Enable(EnableCap.CullFace);

            vao = new Vao();
            shader = new Shader("shader.vs", "shader.fs");
            texture = Texture2D.Load("lightmap.dds");

            mesh = MeshLoader.LoadObjSimple("room.obj");

            vertexBuffer = new Vbo<Vector3>(mesh.Vertices);
            uvBuffer = new Vbo<Vector2>(mesh.Uvs);

            attribs.AddAttrib(3, vertexBuffer);
            attribs.AddAttrib(2, uvBuffer);

        }

        private void Render() {
            shader.Use();
            InputControls.computeMatricesFromInput(this);
            var mvp = Matrix4.Identity * InputControls.ViewMatrix * InputControls.ProjectionMatrix;
            shader.SetMatrix4("MVP", ref mvp);

            texture.Active(TextureUnit.Texture0, shader, "myTextureSampler");

            attribs.Enable();
            GL.DrawArrays(PrimitiveType.Triangles, 0, mesh.Vertices.Length);
            attribs.Disable();
        }

        private void T15_LightMapsGameWindow_Resize(object sender, EventArgs e) {
            GL.Viewport(0, 0, Width, Height);
        }



        private void T15_LightMapsGameWindow_Unload(object sender, EventArgs e) {
            GlDisposableObjectBase.DisposeObjects(vao,shader, texture, vertexBuffer, uvBuffer,mesh);
        }

    }
}
